<template>
    <v-layout>
        <div style="width: 100%;background-color: rgb(239, 239, 239);">
            <div style="margin: 10px;height: 80vh;">
                <v-card height="15%" rounded="lg">
                    <div
                        style="display: flex;align-items: center;height: 100%;padding-left: 2%;justify-content: space-between;">
                        <v-row align="center">
                            <span class="title">课程类别:</span>
                            <el-select size="large" v-model="selectedType" style="width: 150px;"
                                @change="data.currentPage = 1, loadCourseItem({ page: 1, itemsPerPage: data.itemsPerPage })">
                                <el-option v-for="(t, index) in typeList" :key="index" :label="t" :value="t">
                                </el-option>
                            </el-select>
                        </v-row>
                        <v-row style="max-width: 30%;">
                            <el-select size="large" v-model="searchType" style="width: 125px;margin-right: 5%;" @change="() => {
                                clearSearch()
                                if (searchType === '全部') loadCourseItem({ page: data.currentPage, itemsPerPage: data.itemsPerPage })
                            }">
                                <el-option v-for="(t, index) in searchList" :key="index" :label="t" :value="t">
                                </el-option>
                            </el-select>
                            <v-text-field variant="outlined" density="compact" style=" max-width: 200px;"
                                prepend-inner-icon="mdi-magnify" placeholder="搜索..." color="blue" v-model="searchInput"
                                :disabled="searchType === '全部'"
                                @change="changeSearch(), loadCourseItem({ page: data.currentPage, itemsPerPage: data.itemsPerPage })"></v-text-field>
                        </v-row>
                    </div>
                </v-card>
                <div style="height:2%;"></div>
                <v-card height="84%" rounded="lg">
                    <v-container style="padding-left: 1%;margin-left: 0;padding-right: 0;">
                        <v-data-table-server :headers="data.headers" :items-length="data.totalItems"
                            :items="data.courseItems" @update:options="loadCourseItem" :loading="data.isLoading"
                            loading-text="加载中..." density="comfortable" no-data-text="表中无数据" height="55vh" fixed-header
                            hover>
                            <template v-slot:item="{ item }">
                                <tr style="font-size: small;">
                                    <td>{{ item.index }}</td>
                                    <td>{{ item.name }}</td>
                                    <td>{{ item.type }}</td>
                                    <td>{{ item.academy }}</td>
                                    <td>{{ item.teacher }}</td>
                                    <td>{{ item.credit }}</td>
                                    <td>{{ item.location }}</td>
                                    <td>{{ item.formatTime }}</td>
                                    <td>
                                        <a class="action" v-if="!item.action" @click="selectCourse(item)">选课</a>
                                        <a class="action" v-else @click="dropCourse(item)">退选</a>
                                    </td>
                                </tr>
                            </template>
                            <template v-slot:bottom>
                                <v-container style="margin-top: 1%;">
                                    <v-row justify="end" align="center">
                                        <div
                                            style="width: 35%;display: flex;justify-content: space-around;align-items: center;">
                                            <span>每页条数：</span>
                                            <el-select size="large" style="width: 150px;" v-model="data.itemsPerPage"
                                                @change="data.currentPage = 1, loadCourseItem({ page: data.currentPage, itemsPerPage: data.itemsPerPage })">
                                                <el-option :value="10"></el-option>
                                                <el-option :value="20"></el-option>
                                            </el-select>
                                            <v-btn elevation="0" variant="outlined" :disabled="data.currentPage === 1"
                                                color="grey"
                                                @click="data.currentPage--, loadCourseItem({ page: data.currentPage, itemsPerPage: data.itemsPerPage })">
                                                <v-icon icon="mdi-chevron-left" size="24"></v-icon>
                                            </v-btn>
                                            <v-btn elevation="0" variant="outlined" color="grey"
                                                :disabled="data.courseItems.length < data.itemsPerPage"
                                                @click="data.currentPage++, loadCourseItem({ page: data.currentPage, itemsPerPage: data.itemsPerPage })">
                                                <v-icon icon="mdi-chevron-right" size="24"></v-icon>
                                            </v-btn>
                                        </div>
                                    </v-row>
                                </v-container>
                            </template>
                        </v-data-table-server>
                    </v-container>
                </v-card>
            </div>
        </div>
    </v-layout>
</template>
<script setup lang="ts">
import { SearchCourse, SelectCourse, DropCourse } from '@/controllers/courseController';
import { message, messageConfirm } from '@/utils/message';
import { reactive, ref, onMounted } from 'vue';
import { useCourseStore } from '@/stores';
const typeList = ['全部', '必修课', '限选课', '任选课']
const typeNumberList = [3, 0, 1, 2]
const searchList = ['全部', '课程名称', '教师', '课序号']
const searchType = ref('全部')
let selectedType = ref('全部')
let searchInput = ref('')

let data = reactive({
    headers: [
        { title: '课序号', key: 'index', sortable: false },
        { title: '课程名称', key: 'name', sortable: false },
        { title: '课程类别', key: 'type', sortable: false },
        { title: '开课学院', key: 'academy', sortable: false },
        { title: '授课教师', key: 'teacher', sortable: false },
        { title: '学分', key: 'credit', sortable: false },
        { title: '授课地点', key: 'location', sortable: false },
        { title: '开课时间', key: 'formatTime', sortable: false },
        { title: '操作', key: 'action', sortable: false }
    ],
    itemsPerPage: 10,
    totalItems: 0,
    currentPage: 1,
    courseItems: [] as any[],
    isLoading: true,
    name: '',
    index: '',
    teacher: ''
})

onMounted(() => {
    useCourseStore().init()
})

async function searchCourse({ page, pageSize, type, name, index, teacher }: {
    page: number, pageSize: number, type: number,
    name: string
    index: string
    teacher: string
}) {
    try {
        let courseList = (await SearchCourse({ page, pageSize, type, name, index, teacher })) as any[]
        courseList.forEach(
            (val) => {
                let type = val.type
                val.type = type === 0 ? '必修' : type === 1 ? '限选' : '任选'
                val.action = useCourseStore().courses.find(c => c.id === val.id) != undefined
            }
        )
        return ({ items: courseList, total: courseList.length })
    }
    catch (error: any) {
        message(error.message, 'error')
    }
}
function loadCourseItem({ page, itemsPerPage }: { page: number; itemsPerPage: number }) {
    data.isLoading = true
    searchCourse({
        page: page, pageSize: itemsPerPage, type: typeNumberList[typeList.indexOf(selectedType.value)],
        name: data.name, index: data.index, teacher: data.teacher
    }).then(
        (result) => {
            if (result) {
                data.courseItems = result.items || []
                data.totalItems = result.total || 0
            }
            data.isLoading = false
        }
    )
}
async function selectCourse(course: any) {
    let conflictCourse = conflict(course)
    if (conflictCourse !== '') {
        message('当前课程与已选课程"' + conflictCourse + '"冲突', 'error')
        return
    }
    try {
        if (await messageConfirm('确认选择当前课程吗？')) {
            await SelectCourse(course.id)
            useCourseStore().refreshCourseData().then(
                () => {
                    message('选课成功!', 'success')
                    course.action = true
                }
            )
        }
    }
    catch (error: any) {
        return
    }
}
async function dropCourse(course: any) {
    try {
        if (await messageConfirm('确认退选当前课程吗')) {
            await DropCourse(course.id)
            useCourseStore().refreshCourseData().then(
                () => {
                    message('退选成功!', 'success')
                    course.action = false
                }
            )
        }
    }
    catch (error: any) {
        return
    }
}
function changeSearch() {
    switch (searchType.value) {
        case '课程名称': {
            data.name = searchInput.value
            break
        }
        case '课序号': {
            data.index = searchInput.value
            break
        }
        case '教师': {
            data.teacher = searchInput.value
            break
        }
    }
}
function clearSearch() {
    data.name = ''
    data.index = ''
    data.teacher = ''
    searchInput.value = ''
}
function conflict(course: any): string {
    let order = course.order
    let weekday = course.weekday
    let week = course.week as Array<number>
    let courses = useCourseStore().courses
    for (let i = 0; i < courses.length; i++) {
        if (order instanceof Array) {
            for (let j = 0; j < order.length; j++) {
                //节次和日期都相等再判周数是否重叠
                if (courses[i].order === order[j] && courses[i].weekday === weekday[j]) {
                    if (week.some(element => courses[i].week.includes(element))) {
                        return courses[i].name
                    }
                }
            }
        }
        else {
            if (courses[i].order === order && courses[i].weekday === weekday) {
                if (week.some(element => courses[i].week.includes(element))) {
                    return courses[i].name
                }
            }
        }
    }
    return ''
}
</script>
<style scoped>
.title {
    font-weight: bold;
    font-size: 18px;
    margin-right: 1%;
}

.action {
    font-size: 12px;
    color: rgb(0, 89, 255);
    user-select: none;
    cursor: pointer;
    text-decoration: underline;
}
</style>